﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;

namespace LuceneMike
{
    class LuceneManager
    {
        private int IDCounter;
        private Directory IDXdirectory;
        private Analyzer analyser = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
        private IndexWriter writer;
        private Form1 form;

        public LuceneManager(Form1 form)
        {
            this.form = form;
            IDXdirectory = FSDirectory.Open(new System.IO.DirectoryInfo(@"C:\Index"));
            writer = new IndexWriter(IDXdirectory, analyser, true, new IndexWriter.MaxFieldLength(1000));
            
            IDCounter = 0;
        }

        public void loadDocuments(String path)
        {
            string[] filePaths = System.IO.Directory.GetFiles(path, "*.txt");
            Debug.WriteLine("Anzahl der dokumente " + filePaths.Length);

            foreach(String p in filePaths) {
                //string f = readFile(p);
                string name = getName(p);
                
                Document doc = new Document();
                Field fldText = new Field("text", System.IO.File.ReadAllText(p), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES);
                doc.Add(fldText);
                doc.Add(new Field("name", getName(p), Field.Store.YES, Field.Index.NO));
                //doc.Add(new Field("id", getID(), Field.Store.YES, Field.Index.NO));

                writer.AddDocument(doc);
                
            }
            //Optimize
            writer.Optimize();
            writer.Dispose();
            //writer.Close();
            Debug.WriteLine("Indexing Done");
        }

        public void search(string query)
        {
            //string strIndexDir = @"C:\Index";
            Analyzer std = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
            QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "text", std);
            Query qry = parser.Parse(query);

            //Directory directory = FSDirectory.Open(new System.IO.DirectoryInfo(strIndexDir)); //Provide the directory where index is stored
            Searcher srchr = new IndexSearcher(IndexReader.Open(IDXdirectory, true));//true opens the index in read only mode
            
            TopScoreDocCollector cllctr = TopScoreDocCollector.Create(100, true);
            srchr.Search(qry, cllctr);
            ScoreDoc[] hits = cllctr.TopDocs().ScoreDocs;
            Debug.WriteLine("scores "+hits.Length);
            string output = "Gefundene Dokumente: \n\n";
            for (int i = 0; i < hits.Length; i++)
            {

                int docId = hits[i].Doc;
                float score = hits[i].Score;
                Lucene.Net.Documents.Document doc = srchr.Doc(docId);
                Field name = doc.GetField("name");
                Debug.WriteLine("Searched from Text: " +name.StringValue +" "+ score);
                output += score.ToString("0.00000") + "\t" + name.StringValue + "\n";
            }
            form.updateOutput(output);
        }

        private string readFile(String path)
        {
            System.IO.StreamReader myFile = new System.IO.StreamReader(path);
            string myString = myFile.ReadToEnd();

            myFile.Close();
            return myString;
        }

        private string getName(String path)
        {
            int pos = path.LastIndexOf("\\");
            string name = path.Substring(pos+1);
            name = name.Substring(0, name.Length - 4);
            return name;
        }

        private string getID()
        {
            int id = this.IDCounter;
            IDCounter++;
            return id.ToString();
        }
    }
}
